package com.losdun.aftersales.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.losdun.aftersales.domain.ContractOrder;
import com.losdun.aftersales.domain.Repair;
import com.losdun.aftersales.enums.WorkStatusEnum;
import com.losdun.aftersales.manager.NoticeManager;
import com.losdun.aftersales.manager.NumberGenerator;
import com.losdun.aftersales.mapper.RepairMapper;
import com.losdun.aftersales.service.IContractOrderService;
import com.losdun.aftersales.service.IRepairService;
import com.losdun.common.constant.HttpStatus;
import com.losdun.common.exception.ServiceException;
import com.losdun.common.utils.DateUtils;
import com.losdun.common.utils.uuid.CodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 售后维保Service业务层处理
 * 
 * @author swordye
 * @date 2025-08-19
 */
@Service
public class RepairServiceImpl extends ServiceImpl<RepairMapper,Repair> implements IRepairService
{
    @Autowired
    private RepairMapper repairMapper;

    @Autowired
    private IContractOrderService contractOrderService;
    @Autowired
    private NumberGenerator numberGenerator;

    @Autowired
    private NoticeManager noticeManager;

    /**
     * 查询售后维保
     * 
     * @param id 售后维保主键
     * @return 售后维保
     */
    @Override
    public Repair selectRepairById(Long id)
    {
        return repairMapper.selectRepairById(id);
    }

    /**
     * 查询售后维保列表
     * 
     * @param repair 售后维保
     * @return 售后维保
     */
    @Override
    public List<Repair> selectRepairList(Repair repair)
    {
        return repairMapper.selectRepairList(repair);
    }

    /**
     * 新增售后维保
     * 
     * @param repair 售后维保
     * @return 结果
     */
    @Override
    public int insertRepair(Repair repair)
    {
        repair.setCreateTime(DateUtils.getNowDate());
        return repairMapper.insertRepair(repair);
    }

    /**
     * 修改售后维保
     * 
     * @param repair 售后维保
     * @return 结果
     */
    @Override
    public int updateRepair(Repair repair)
    {
        repair.setUpdateTime(DateUtils.getNowDate());
        return repairMapper.updateRepair(repair);
    }

    /**
     * 批量删除售后维保
     * 
     * @param ids 需要删除的售后维保主键
     * @return 结果
     */
    @Override
    public int deleteRepairByIds(Long[] ids)
    {
        return repairMapper.deleteRepairByIds(ids);
    }

    /**
     * 删除售后维保信息
     * 
     * @param id 售后维保主键
     * @return 结果
     */
    @Override
    public int deleteRepairById(Long id)
    {
        return repairMapper.deleteRepairById(id);
    }

    @Override
    public void appInsertRepair(Repair repair) {
        ContractOrder order = contractOrderService.selectContractOrderById(repair.getOrderId());
        if(order== null){
            throw new ServiceException("原始订单不存在！", HttpStatus.SERVICE_EXCEPTION);
        }
        if(checkRepairExists(repair.getOrderId())){
            throw new ServiceException("此订单已报修，请等待师傅上门处理！", HttpStatus.SERVICE_EXCEPTION);
        }
        repair.setCreateTime(DateUtils.getNowDate());
        repair.setWorkNo(numberGenerator.generateNo("RWO"));
        repair.setFinishCode(CodeUtils.generateNumberCode(4));
        baseMapper.insertRepair(repair);

        //发送通知
        noticeManager.bookRepairSuccessSendNotice(order,repair);

    }

    @Override
    public void completedRepair(Long id, String finishCode) {
        Repair repair = this.getById(id);
        if(repair==null){
            throw new RuntimeException("售后工单不存在！");
        }
        if(!repair.getFinishCode().equals(finishCode)){
            throw new RuntimeException("验证码错误！");
        }
        repair.setStatus(WorkStatusEnum.COMPLETED.getValue());
        repair.setFinishTime(DateUtils.getNowDate());
        baseMapper.updateRepair(repair);
        //发送通知
        noticeManager.repairCompletedSendNotice(repair);
    }

    @Override
    public List<Repair> queryUnCompletedRepair() {
        LambdaQueryWrapper<Repair> qw=new LambdaQueryWrapper<>();
        qw.ne(Repair::getStatus,WorkStatusEnum.COMPLETED.getValue());
        return baseMapper.selectList(qw);
    }

    @Override
    public List<Repair> queryRepairByOrderId(Long orderId) {
        return baseMapper.selectList(new LambdaQueryWrapper<Repair>().eq(Repair::getOrderId,orderId));
    }

    @Override
    public boolean checkChangeWorker(Repair repair) {
        if(repair.getWorkerId()==null){
            return false;
        }
        Repair old = baseMapper.selectById(repair.getId());
        return !repair.getWorkerId().equals(old.getWorkerId());
    }

    /**
     * 存在未完成的订单
     * @param orderId
     * @return
     */
    private boolean checkRepairExists(Long orderId){
        LambdaQueryWrapper<Repair> qw=new LambdaQueryWrapper<>();
        qw.eq(Repair::getOrderId,orderId).ne(Repair::getStatus,2);
        return this.count(qw)>0;
    }

}
